//
//  LoginViewController.m
//  月色:(我)
//
//  Created by 殷殷明静 on 16/9/8.
//  Copyright © 2016年 MJ.Y. All rights reserved.
//
#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
#define COLOR_TIP [UIColor colorWithRed:152 / 256.0 green:152 / 256.0 blue:152 / 256.0 alpha:1]
#import "LoginViewController.h"
#import "CustomTextField.h"
#import "AFNetworking.h"
#import "NSString+JHMD5.h"
#import "MyViewController.h"
@interface LoginViewController ()<UITextFieldDelegate>
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) CustomTextField *phoneTextField;
@property (nonatomic, strong) CustomTextField *passwordTextField;
@property (nonatomic, strong) UIView *redLineView;
@property (nonatomic, strong) UIButton *cleanBtn;
@property (nonatomic, strong) UIButton *completeBtn;
@property (nonatomic, strong) NSDictionary *dic;
@property (nonatomic, strong) UIActivityIndicatorView *activityIndicator;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self initNavigationLeftButton];
    // 请输入手机号
    [self createPhoneTextField];
    // 请输入密码
    [self inputPassword];
    // 完成
    [self completeButton];
    // 轻点击回收键盘
    [self resignKeyBoard];
}
// 密码textField
- (void)inputPassword {
    _passwordTextField = [[CustomTextField alloc] init];
    [self.view addSubview:_passwordTextField];
    _passwordTextField.frame = CGRectMake(0, 0, 120,30);
    _passwordTextField.center = CGPointMake(WIDTH / 2 + 20, 160);
    _passwordTextField.placeholder = @"请输入密码";
    _passwordTextField.secureTextEntry = YES;
    // 签协议
    _passwordTextField.delegate = self;
    // 通知中心监听限制字符
    [_passwordTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}
// 电话号码textField
- (void)createPhoneTextField {
    _phoneTextField = [[CustomTextField alloc] init];
    [self.view addSubview:_phoneTextField];
    _phoneTextField.frame = CGRectMake(0, 0, 100,30);
    _phoneTextField.center = CGPointMake(WIDTH / 2 + 10, 110);
    _phoneTextField.placeholder = @"请输入手机号";
    _phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    // 线
    _redLineView = [[UIView alloc] init];
    [self.view addSubview:_redLineView];
    _redLineView.frame = CGRectMake(0, 0, 180, 1);
    _redLineView.center = CGPointMake(WIDTH / 2, 130);
    _redLineView.backgroundColor = [UIColor redColor];
    // 签协议
    _phoneTextField.delegate = self;
    // 通知中心监听限制字符
    [_phoneTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}
// 限制字符输入个数,以及发送验证码按钮变红色
- (void)textFieldDidChange:(UITextField *)textField {
    if ([textField isEqual:_phoneTextField]) {
        // 限制手机号码字符长度为11
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }  else if ([textField isEqual:_passwordTextField]) {
            if (textField.text.length > 12) {
                // 限制密码字符长度为12
                textField.text = [textField.text substringToIndex:12];
            }
        }
    }
}
// 键盘return 回收
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
// 自定义导航栏样式
- (void)initNavigationLeftButton {
    _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_backBtn];
    _backBtn.frame = CGRectMake(20, 20, 20, 20);
    [_backBtn setBackgroundImage:[UIImage imageNamed:@"Icon_jiantou"] forState:0];
    [_backBtn addTarget:self action:@selector(backToLoginAndRegisterViewController) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_backBtn];
    // 标题
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 44, 30)];
    titleLabel.text = @"登录";
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.font = [UIFont systemFontOfSize:13];
    titleLabel.textAlignment = 1;
    self.navigationItem.titleView = titleLabel;
}
// pop返回
- (void)backToLoginAndRegisterViewController {
    [self.navigationController popViewControllerAnimated:YES];
}
// 自定义导航栏shadowImage的横线
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    self.navigationController.navigationBar.shadowImage = [UIImage imageNamed:@"Icon_line"];
    // 自动弹出键盘
    [_phoneTextField becomeFirstResponder];
}
// 视图消失,横线透明
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
}
// 自定义清除按钮的协议方法
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField isEqual:_phoneTextField]) {
        if (textField.text.length > 0) {
            // 记得调用懒加载
            self.cleanBtn.hidden = NO;
        } else {
            self.cleanBtn.hidden = YES;
        }
        
    }
    return YES;
}
// 懒加载self.cleanBtn
- (UIButton *)cleanBtn {
    if (!_cleanBtn) {
        // 自定义清除按钮
        _cleanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.view addSubview:_cleanBtn];
        _cleanBtn.frame = CGRectMake(0, 0, 15, 15);
        _cleanBtn.center = CGPointMake(WIDTH / 2 + 80, 110);
        [_cleanBtn setBackgroundImage:[UIImage imageNamed:@"Icon_chacha"] forState:0];
        [_cleanBtn addTarget:self action:@selector(cleanAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cleanBtn;
}
// 清空textFiled
- (void)cleanAction {
    _phoneTextField.text = nil;
    _cleanBtn.hidden = YES;
}
// 注册button
- (void)completeButton {
    _completeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_completeBtn];
    _completeBtn.frame = CGRectMake(0, 0, 44, 44);
    _completeBtn.center = CGPointMake(WIDTH / 2, 280);
    _completeBtn.layer.cornerRadius = 22;
    _completeBtn.layer.borderWidth = 1;
    _completeBtn.layer.borderColor = [UIColor redColor].CGColor;
    [_completeBtn setBackgroundImage:[UIImage imageNamed:@"Icon_registerComplete"] forState:0];
    // 注册
    [_completeBtn addTarget:self action:@selector(sendLoginRequest) forControlEvents:UIControlEventTouchUpInside];
}
// 发送注册网络请求
- (void)sendLoginRequest {
    // 小菊花转起来
    [self createActivityIndicatorView];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    // 请求头
    [manager.requestSerializer setValue:@"Dalvik/1.6.0 (Linux; U; Android 4.2.1; R823T Build/JOP40D) Liuda/2.2.0 (agent:s;channel:360;credential:e1MxMDEwMDAxMDF9LXsjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIzg2MzMzMTAyODY3NDU0Mn0teyMjIyMjIyMxNDczMTU1OTc5ODA3LTQzNTkzYTY2M2R9QDE0NzI0MTc2MzEzMDE=;deviceId:863331028674542;osTypeId:01;detailInfo:android;simTypeId:01;netTypeId:01;deviceTypeId:01;osVersion:4.2.1;idfa:null)" forHTTPHeaderField:@"User-Agent"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    // BODY体
    // 转MD5
    NSString *passwordMD5 = [_passwordTextField.text stringWith32BitMD5Lower];
    // 根据textField.text生成body体
    NSDictionary *parameters = @{@"mobile":_phoneTextField.text,@"pwd":passwordMD5};
    // POST
    [manager POST:@"http://login.9liuda.com/v1/user/login" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 小菊花停止
        [self.activityIndicator stopAnimating];
        
        _dic = responseObject;
        if (![_dic.allValues containsObject:@"ok"]) {
            // 注册失败
            // 打印消息
            [self createTipLabel_failed];
        } else {
            // 注册成功
            // 跳转页面
            MyViewController *myVC = (MyViewController *)self.navigationController.viewControllers.firstObject;
            myVC.isLogined = YES;
            myVC.nickName = _dic[@"data"][@"nickName"];
            myVC.portrait = _dic[@"data"][@"portrait"];
            NSLog(@"%@",_dic[@"data"][@"nickName"]);
//           
            [self.navigationController popToRootViewControllerAnimated:YES];
            
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
}

// 提示label:失败状态
- (void)createTipLabel_failed {
    UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, WIDTH - 70, 30)];
    tipLabel.center = CGPointMake(WIDTH / 2, HEIGHT / 2);
    tipLabel.backgroundColor = COLOR_TIP;
//    tipLabel.layer.borderWidth = 1;
//    tipLabel.layer.borderColor = [UIColor blackColor].CGColor;
    tipLabel.textAlignment = 1;
    tipLabel.text = _dic[@"message"];
    tipLabel.textColor = [UIColor whiteColor];
    tipLabel.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:tipLabel];
    [UIView animateWithDuration:4.0 animations:^{
        tipLabel.alpha = 0.0;
    } completion:^(BOOL finished) {
        [tipLabel removeFromSuperview];
    }];
}
// 轻点空白回收键盘
- (void)resignKeyBoard {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignFirstResponderKeyBoard:)];
    [self.view addGestureRecognizer:tap];
}
- (void)resignFirstResponderKeyBoard:(UITapGestureRecognizer *)tap {
    [_phoneTextField resignFirstResponder];
    [_passwordTextField resignFirstResponder];
}
// 小菊花懒加载
- (UIActivityIndicatorView *)activityIndicator {
    if (!_activityIndicator) {
        _activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
        _activityIndicator.center = CGPointMake(WIDTH / 2, HEIGHT / 2);
        _activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
        _activityIndicator.color = COLOR_TIP;
        [self.view addSubview:_activityIndicator];
    }
    return _activityIndicator;
}
- (void)createActivityIndicatorView {
    [self.activityIndicator startAnimating];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
